package com.antdant.service;

import com.antdant.exception.GeneralException;
import com.antdant.utils.DataUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author Lee Yunc
 * @Date 2021/2/23 15:28
 * @Description:
 * @Version 1.0
 */
@Component
public class RedisService {

    private static final Logger logger = LoggerFactory.getLogger(RedisService.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 设置缓存生效时间
     *
     * @param key
     * @param time
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            logger.error("RedisService.expire failed,key:{},time:{}", key, time, e);
            throw new GeneralException("设置超时失效");
        }
    }


    /**
     * 通过key查询token
     *
     * @param key
     * @return
     */
    public String get(String key) {
        try {
            return redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            logger.error("RedisService.get failed,key:{},Error:", key, e);
            throw new GeneralException("cache redis failed");
        }
    }

    /**
     * 缓存用户信息
     *
     * @param key
     * @param value （用户信息json串）
     * @param timeOut
     */
    public void set(String key, String value, long timeOut) {
        try {
            redisTemplate.opsForValue().set(key, value);
            if (DataUtils.isNotNull(timeOut) && timeOut > 0) {
                expire(key, timeOut);
            }
        } catch (Exception e) {
            logger.error("RedisService.set failed,key:{},Error:", key, e);
            throw new GeneralException("cache redis failed");
        }
    }

    /**
     * 判断缓存key是否存在
     *
     * @param cacheKey
     * @return
     */
    public boolean hasKey(String cacheKey) {
        try {
            return redisTemplate.hasKey(cacheKey);
        } catch (Exception e) {
            logger.error("RedisService.hasKey failed,key:{},Error:", cacheKey, e);
            throw new GeneralException("验证key失败");
        }
    }

    /**
     * 通过key删除缓存信息
     *
     * @param cacheKey
     */
    public void delete(String cacheKey) {
        try {
            redisTemplate.delete(cacheKey);
        } catch (Exception e) {
            logger.error("delete failed,Error:", e);
        }
    }
}
